package com.heima.juc.unlock;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author : leimingchao
 * @date Date : 2022年02月12日 22:29
 */
@Slf4j(topic = "c.TestUnsafe2")
public class TestUnsafe2 {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unSafe = (Unsafe) theUnsafe.get(null);
        System.out.println(unSafe);

        //1.获取域的偏移地址
        long idOffset = unSafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
        long nameOffset = unSafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));

        Teacher teacher = new Teacher();
        //2.执行cas操作
        unSafe.compareAndSwapInt(teacher, idOffset,0,1);
        unSafe.compareAndSwapObject(teacher, nameOffset, null, "张三");

        //3.验证结果
        System.out.println(teacher);
    }
}

@Data
class Teacher {

    volatile int id;

    volatile String name;

}
